﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Management;

namespace Frame.Host
{
    public partial class MainForm : Form
    {
        bool _isClose = false;

        public MainForm()
        {
            InitializeComponent();
            this.notifyIcon.Visible = true;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            textBox_ip.Text = GetLocalIPAddress();
        }

        public static string GetLocalIPAddress()
        {
            string pattern = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";
            string strmac = "";
            string strip = "";
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject mo in queryCollection)
            {
                if (mo["IPEnabled"].ToString() == "True")
                {
                    strip = (mo["IPAddress"] as String[])[0];
                    strmac = mo["MacAddress"].ToString();

                    if (Regex.IsMatch(strip, pattern) == true)
                    {
                        break;
                    }
                }
            }
            return strip;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!_isClose)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible) this.Hide();
            else this.Show();
        }

        private void button_Start_Click(object sender, EventArgs e)
        {
            try
            {
                WcfService.Process.Start(textBox_ip.Text.Trim(), textBox_port.Text.Trim());
                label_state.Text = "Start Success...";
                button_Start.Enabled = false;
            }
            catch (Exception ex)
            {
                label_state.Text = "Fail Start. Exception Message" + ex.Message;
            }
        }

        private void button_Stop_Click(object sender, EventArgs e)
        {
            CloseFrom();
        }
        private void CloseFrom()
        {
            this._isClose = true;
            WcfService.Process.Stop();
            this.Close();
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseFrom();
        }
    }
}
